package top.jolyoulu.core.rdd.operator.transform

import org.apache.spark.rdd.RDD
import org.apache.spark.{HashPartitioner, SparkConf, SparkContext}

/**
 * @Author: JolyouLu
 * @Date: 2024/2/7 20:51
 * @Description
 */
object Spark015_RDD_Operator_ReduceByKey {
  def main(args: Array[String]): Unit = {
    //准备环境 [*]:表示使用当前系统最大核
    val sparkConf: SparkConf = new SparkConf().setMaster("local[*]").setAppName("RDD")
    val sc: SparkContext = new SparkContext(sparkConf)

    val rdd: RDD[(String, Int)] = sc.makeRDD(List(
      ("a", 1), ("a", 2), ("a", 3), ("b", 4)
    ))
    //将相同的key数据的value进行聚合
    // ("a", 1), ("a", 2) 聚合得到 ("a", 3)
    // ("a", 3), ("a", 3) 聚合得到 ("a", 6)
    val reduceRDD: RDD[(String, Int)] = rdd.reduceByKey((x: Int, y: Int) => {
      x + y
    })
    reduceRDD.collect().foreach(println)
    //关闭环境
    sc.stop()
  }

}
